package Web5;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ServletDeo7 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Date date=new Date();
        //将date转换成字符串
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format=sdf.format(date);
        //解析特殊符号
        format= URLEncoder.encode(format,"utf-8");
        //创建Cookie对象将时间传递给浏览器
        Cookie cookie=new Cookie("lastname",format);
        response.addCookie(cookie);
        //3 获取cookie记录的时间输出为上一次访问的时间
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie1 : cookies) {
            if ("lastname".equals(cookie.getName())){
                String decode = URLDecoder.decode(format, "utf-8");
                //在浏览器上输出
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().println("您上次访问的时间是："+decode);

            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
    }
}
